package kuaipan.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.activation.MimetypesFileTypeMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
/*
 * 公共工具类
 */
public class CommUtil {
	//生成随机字符串（小于22字节）本例为8个字符
	public static String getRandom() {
		Random rd1 = new Random();
		String[] c = {"1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
		StringBuffer buffer = new StringBuffer();
		for(int i = 0;i < 8; i++) {
			buffer.append(c[rd1.nextInt(c.length)]);
		}
		return buffer.toString();
	}
	//urlencode 转换工具
	public static String urlToEncode(String str) throws UnsupportedEncodingException {
		return java.net.URLEncoder.encode(str,"utf-8");
	}
	
	//模拟http get 请求
	public static Map<String,String> httpRequest(String sUrl, String charset) throws IOException {
		Map<String,String> map = new HashMap<String, String>();
		int HttpResult;
		URL url = new URL(sUrl);
		URLConnection urlconn = url.openConnection();
		// 抽象类 URLConnection
		// 是所有类的超类，它代表应用程序和 URL
		// 之间的通信链接，通过在 URL 上调用
		// openConnection 方法创建连接对象
		urlconn.connect(); // 使用 connect 方法建立到远程对象的实际连接
		HttpURLConnection httpconn = (HttpURLConnection) urlconn;
		// 每个
		// HttpURLConnection
		// 实例都可用于生成单个请求，
		// 但是其他实例可以透明地共享连接到
		// HTTP 服务器的基础网络
		HttpResult = httpconn.getResponseCode();
		// getResponseCode可以从 HTTP
		// 响应消息获取状态码
		if (HttpResult != HttpURLConnection.HTTP_OK) {
//			Log.showLog("系统信息：" + HttpResult);
			System.out.println("系统信息：" + HttpResult);
			map.put("state", HttpResult + "");
		} else {
			InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), charset);
			BufferedReader in = new BufferedReader(isr);
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				map = Analytic(inputLine);
			}
			map.put("state", 0 + "");
			in.close();
		}
		return map;
	}
	
	/*
	 * 解析返回结果
	 */
	public static Map<String,String> Analytic(String parameter) {
		Map<String,String> map = new HashMap<String, String>();
		String[] fathers = parameter.replace("{", "").replace("}", "").replace("\"", "").replace(" ", "").split(",");
		for (String father : fathers) {
			System.out.println(father.split(":")[0]+":"+father.split(":")[1]);
			map.put(father.split(":")[0], father.split(":")[1]);
		}
		return map;
	}

	/*
     * 下载文件
     */
    public static void DownFile(String url,String fileName) throws Exception {
    	DefaultHttpClient hc = new DefaultHttpClient();

		hc.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
		hc.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,"UTF-8"); // 默认为ISO-8859-1
		hc.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET,"UTF-8"); // 默认为US-ASCII

		HttpGet hGet = new HttpGet(url);
		
		HttpResponse response = hc.execute(hGet);
		InputStream is = response.getEntity().getContent();
		byte buffer[] = new byte[2048];

		// 读取数据长度
		int len;

		// 输出的文件流
		OutputStream os = new FileOutputStream(fileName);

		// 读取数据
		while ((len = is.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		
		// 完毕关闭所有链接
		os.close();
		is.close();
		 //垃圾回收
        System.gc();
    }
    
    /*
     * 上传文件,增加上传文件的方式，by jackguoxz,  by jackguoxz http://blog.sina.com.cn/jackguoxz
     */
    public static void UploadFile(String url,String fileName) throws Exception {
    
    	File file = new File(fileName);
        HttpClient hc = new HttpClient();
    	PostMethod post = new PostMethod(url);
        String responseString = null;
        try {
            FilePart filePart = new FilePart("file", file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8");
            filePart.setTransferEncoding("binary");
            Part[] parts = new Part[] { filePart };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            int responseCode = hc.executeMethod(post);
            if (responseCode == 200) {
                responseString = post.getResponseBodyAsString();
            } else{
                throw new Exception(post.getStatusText()+"response code is "+responseCode);
            }
        } catch (FileNotFoundException fe) {
            throw new Exception(" File does not exist!"+fe.toString());
        } catch (HttpException he) {
            throw new Exception("Problems with http protocol"+he.toString());
        } catch (IOException ioe) {
            throw new Exception("Problems while uploading the file"+ioe.toString());
        } finally {
            post.releaseConnection();
        }
    }
    
    /*
     * 获取计算机mac地址
     */
    public static String getMacAddress() {
    	return MacAddress.getMacAddress();
    }
}